package com.mlst.tagalogtranslator;

import com.google.api.translate.Language;
import com.google.api.translate.Translate;
import com.google.wave.api.AbstractRobotServlet;
import com.google.wave.api.Blip;
import com.google.wave.api.Event;
import com.google.wave.api.EventType;
import com.google.wave.api.RobotMessageBundle;
import com.google.wave.api.TextView;
import com.google.wave.api.Wavelet;

@SuppressWarnings("serial")
public class TagalogTranslatorServlet extends AbstractRobotServlet {

    @Override
    public void processEvents(RobotMessageBundle bundle) {
	final Wavelet wavelet = bundle.getWavelet();

	if (bundle.wasSelfAdded()) {
	    final Blip blip = wavelet.appendBlip();
	    final TextView textView = blip.getDocument();
	    textView.append("Hi, I will translate English to Tagalog for you. Mabuhay, akin pong isasalin ang wikang Ingles sa wikang Tagalog para po sa inyo.");
	}

	for (Event event : bundle.getEvents()) {
	    if (event.getType() == EventType.BLIP_SUBMITTED) {
		final String blipText = event.getBlip().getDocument().getText();

		Translate.setHttpReferrer("http://tagalogify.appspot.com");
		String translatedText = "";
		
		try {
		    translatedText = Translate.translate(blipText, Language.ENGLISH, Language.FILIPINO);
		} catch (Exception e) {
		    e.printStackTrace();
		}

		String markup = "";
		
		if (translatedText != null) {
		    markup = "<br/>" + translatedText;
		}

		event.getBlip().getDocument().appendMarkup(markup);
	    }
	}
    }

}
